package com.zengdada.authority.controller;

import com.zengdada.authority.utils.JsonMessage;
import io.swagger.annotations.Api;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
//import java.util.List;

/**
 * @Auther: 12614
 * @Contact: 1261438511@qq.com
 * @Date: 2018/11/13 17:24
 * @Description:
 */
@Api(hidden = true)
@Controller
public class MyErrorAuthorityController implements ErrorController {

    private static final String ERROR_PATH = "/error";

    private static DefaultErrorAttributes defaultErrorAttributes = new DefaultErrorAttributes();

    public MyErrorAuthorityController() {
        super();
    }


    @RequestMapping(value = ERROR_PATH, produces = "text/html")
    public String handleError(HttpServletRequest request) {
        Map<String, Object> errorAttributes = defaultErrorAttributes.getErrorAttributes(new ServletWebRequest(request), false);
        request.setAttribute("errorMsg", String.valueOf(errorAttributes.get("message")));
        int value = getStatus(request).value();
        if (value == 404)
            return "authority/error/404";
        else if (value == 403)
            return "authority/error/403";
        else return "authority/error/500";
    }

    @RequestMapping(value = ERROR_PATH)
    @ResponseBody
    public JsonMessage handleError1(HttpServletRequest request) {
        Map<String, Object> errorAttributes = defaultErrorAttributes.getErrorAttributes(new ServletWebRequest(request), false);
        return JsonMessage.fail(String.valueOf(errorAttributes.get("message")), getStatus(request).value(), errorAttributes);
    }

    public String getErrorPath() {
        return ERROR_PATH;
    }


    protected HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}
